import requests


class TestCookieVerify:

    # ================================================ 直接通过 cookie 参数 ============================================
    def test_cookies_by_write(self):
        # 简单场景，直接写入 cookie
        url = 'https://httpbin.ceshiren.com/cookies'
        res = requests.get(url)
        print(res.json())
        # 传入 cookie 后
        cookie_res = requests.get(url, verify=False, cookies={'hogwarts': 'AD'})
        print(cookie_res.json())

    def test_cookies_without_session(self):
        # 获取 session 的实例，需要通过 Session() 保持会话
        # 即为认证之后，之后所有的实例都会携带 cookie
        # 可以模仿用户在浏览器的操作
        req = requests.Session()
        # 第一次登录，获取 cookie
        set_url = 'https://httpbin.ceshiren.com/cookies/set/hogwarts/ad'
        res1 = req.get(set_url, verify=False)
        print(res1.json())
        # 第二次请求的时候，即可携带 cookie  信息
        url = 'https://httpbin.ceshiren.com/cookies'
        res2 = req.get(url, verify=False)
        print(res2.json())


class TestTokenVerify:
    def test_litemall_token(self):
        # 登录 获取 token
        url = 'http://litemall.hogwarts.ceshiren.com/admin/auth/login'
        user_data = {'username': 'admin123', 'password': 'admin123', 'code': ''}
        r = requests.post(url, json=user_data, verify=False)
        # 结果为 ： {'errno': 0, 'data': {'adminInfo': {'nickName': 'admin123', 'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'}, 'token': 'f3e68dd8-0eca-4e77-b2ed-f2de05083fc3'}, 'errmsg': '成功'}
        print(r.json())
        self.token = r.json()['data']['token']
        print(self.token)
        # 之后的请求均携带 token
        good_list_url = 'http://litemall.hogwarts.ceshiren.com/admin/goods/list'
        goods_data = {'name': 'hogwarts', 'order': 'desc', 'sort': 'add_time'}
        r_token = requests.get(good_list_url, json=goods_data, headers={'X-Litemall-Admin-Token': self.token},
                               verify=False)
        print(r_token.json())
        assert r_token.json()['errno'] == 0
        assert r_token.json()['data']['list'][0]['id'] == 1183302

from requests.auth import HTTPBasicAuth

class TestAuthVerify:
    def test_basic_auth(self):
        # 表示访问一个需要 BasicAuth 认证的路径
        # username=用户名,password=密码
        # 如果不使用 basic auth ，则会失败
        r = requests.get('https://httpbin.ceshiren.com/basic-auth/username/password', verify=False,
                         auth=HTTPBasicAuth('username', 'password'))
        print(r.json())